﻿using Furion;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using LNSServer.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;

namespace LNSServer.Controllers
{
    /// <summary>
    /// 系统初始化
    /// </summary>
    [ApiDescriptionSettings(Order = 5000)]
    public class LnsInitController : IDynamicApiController
    {
        private readonly ILogger<LnsInitController> logger;
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public LnsInitController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
            this.logger = logger;
        }

        /// <summary>
        /// 初始化数据库、表结构、默认数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateDbAndTables()
        {
            #region 创建数据库并修改编码
            //db.DbMaintenance.CreateDatabase("lnsserver");
            //await db.Ado.ExecuteCommandAsync("ALTER DATABASE `lnsserver` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            #endregion

            #region 创建表
            //db.CodeFirst.InitTables<ResourcePool>();
            //db.CodeFirst.InitTables<Tag>();
            //db.CodeFirst.InitTables<User>();
            //db.CodeFirst.InitTables<MapModel>();
            //db.CodeFirst.InitTables<Robot>();
            db.CodeFirst.InitTables<Sensor>();
            //db.CodeFirst.InitTables<ReportModel>();
            // 读取传感器json数据并插入数据库
            JObject data = JObject.Parse(await File.ReadAllTextAsync(Path.Combine(App.WebHostEnvironment.WebRootPath, "2022-02-15-传感器配置模板.json")));
            foreach (var json in data["data"])
            {
                await db.Insertable<Sensor>(new Sensor { Name = json["name"].ToString(), AssetGuid = json["assetGuid"].ToString(), Params = JArray.FromObject(json["params"]), IsActive = 1, Created = DateTime.Now, Updated = DateTime.Now }).ExecuteCommandAsync();
            }
            //db.CodeFirst.InitTables<Project>();
            //db.CodeFirst.InitTables<ProjectTestResult>();
            //db.CodeFirst.InitTables<TestUseCase>();
            #endregion

            #region 生成不可删除的默认基数据和字典表   性别、机种、审批状态、审批类型

            #endregion

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = "初始化数据库、表结构、默认数据成功！！！",
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 测试接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Test()
        {
            Type t = typeof(Animal);
            t.GetConstructors().ToList().ForEach(c => {
                Console.WriteLine($">>>>>>>>>>> {c.GetCustomAttribute<Custom1Attribute>().Height}");
            });

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = t,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Constructor | AttributeTargets.Method)]
    public class Custom1Attribute: Attribute
    {
        public Custom1Attribute(string height, int width) { 
            this.Height = height;
            this.Width = width;
        }

        public string Height { get; set; }

        public int Width { get; set; }
    }

    [Custom1("chang1", 123)]
    public class Animal {

        [Custom1("构造", 0)]
        public Animal() { } 

        [Custom1("属性chang", 1)]
        public int Chang { get; set; }

        [Custom1("属性kuan", 2)]
        public int Kuan { get; set; }

        [Custom1("方法say", 3)]
        public string say() {
            return "哈哈";
        }

    }
}
